package com.cyy.learn.qRCodeBuilder

import com.cyy.app.MyApp
import tornadofx.*
import javax.imageio.ImageIO
import com.tulskiy.keymaster.common.Provider
import javafx.embed.swing.SwingFXUtils
import javafx.stage.FileChooser
import javafx.application.Platform
import java.awt.event.InputEvent
import javax.swing.KeyStroke
import org.apache.commons.lang3.StringUtils
import java.text.SimpleDateFormat
import java.util.*
import com.cyy.util.*
import javafx.scene.image.Image
import com.cyy.util.TooltipUtil
import com.cyy.util.QRCodeUtil
import java.awt.Rectangle
import java.awt.Robot
import java.awt.Toolkit


class QRCodeBuilderController : Controller() {
    val mainStage=MyApp.stage
    var provider = Provider.getCurrentProvider(false)
    fun builderAction(){
        if (StringUtils.isEmpty(contentTextField.value)) {
            return
        }
        try {
            val image = QRCodeUtil.toImage(contentTextField.value, codeImageView.fitWidth.toInt(),
                    codeImageView.fitHeight.toInt(), codeFormat.value,
                    errorCorrectionLevel.value, marginChoice.value, frontColor.value,
                    backColor.value, imageFormat.value)
            codeImageView.image = image
            if (logoCheck.value && codeImageView1.image != null) {
                val image1 = QRCodeUtil.encodeImgLogo(image, codeImageView1.image, logoSlider.value)
                codeImageView.image = image1
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
    fun logoAction(){
        val file = FileChooserUtil.chooseFile(FileChooser.ExtensionFilter("All Images", "*.*"),
                FileChooser.ExtensionFilter("JPG", "*.jpg"), FileChooser.ExtensionFilter("PNG", "*.png"),
                FileChooser.ExtensionFilter("gif", "*.gif"), FileChooser.ExtensionFilter("jpeg", "*.jpeg"),
                FileChooser.ExtensionFilter("bmp", "*.bmp"))
        if (file != null) {
            val image = SwingFXUtils.toFXImage(ImageIO.read(file), null)
            codeImageView1.image = image
        }
    }
    fun snapshotAction(){
        // 默认情况下，Fx运行时会在最后一个stage的close(或hide)后自动关闭，即自动调用Application.stop()
        // 除非通过Platform.setImplicitExit(false)取消这个默认行为。这样,即使所有Fx窗口关闭（或隐藏）,Fx运行时还在正常运行
        Platform.setImplicitExit(false)
        // Main.getStage().setIconified(true);
        if (mainStage.isShowing()) {
            Platform.runLater { mainStage.hide() }
        }
        // new SnapshotRectUtil(this);
        ScreenShoter(this)
    }
    fun snapshotDesktopAction(){
        Platform.setImplicitExit(false)
        try {
            mainStage.hide()
            val SCREEN_SIZE = Toolkit.getDefaultToolkit().screenSize
            val robot = Robot()
            val screenImg = robot.createScreenCapture(
                    Rectangle(0, 0, SCREEN_SIZE.width, SCREEN_SIZE.height))
            mainStage.show()
            val code = QRCodeUtil.toDecode(screenImg)
            if (StringUtils.isNotEmpty(code)) {
                contentTextField.value=code
            } else {
                Platform.runLater { TooltipUtil.showToast("未识别到二维码。") }
            }
        } catch (e: Exception) {
            TooltipUtil.showToast("发生异常:" + e.message)
        } finally {
            Platform.setImplicitExit(true)
        }
    }
    fun saveAction(){
        val fileName = "x" + SimpleDateFormat("yyyyMMddHHmm").format(Date()) + "." + imageFormat.value
        val file = FileChooserUtil.chooseSaveFile(fileName, FileChooser.ExtensionFilter("All Images", "*.*"),
                FileChooser.ExtensionFilter("JPG", "*.jpg"), FileChooser.ExtensionFilter("PNG", "*.png"),
                FileChooser.ExtensionFilter("gif", "*.gif"), FileChooser.ExtensionFilter("jpeg", "*.jpeg"),
                FileChooser.ExtensionFilter("bmp", "*.bmp"))
        if (file != null) {
            val fileType = file.path.split("\\.")
            ImageIO.write(SwingFXUtils.fromFXImage(codeImageView.image, null), fileType[fileType.size - 1],
                    file)
            TooltipUtil.showToast("保存图片成功,图片在：" + file.path)
        }
    }
    /**
     * 父控件被移除前调用
     */
    fun onCloseRequest() {
        try {
            if (provider != null) {
                provider.reset()
                provider.stop()
            }
        } catch (e: Exception) {
            Error("停止快捷键监听失败：", e)
        }

    }

    init {
        initEvent()
    }

    private fun initEvent() {
        try {
            provider = Provider.getCurrentProvider(false)
            provider.register(KeyStroke.getKeyStroke('S', InputEvent.ALT_DOWN_MASK)) { _ -> snapshotAction() }
            TooltipUtil.showToast("按alt+s可快速截图识别！！！")
        } catch (e: Exception) {
            TooltipUtil.showToast("热键注册失败。")
        }

        contentTextField.addListener { _, _, _ -> Platform.runLater { builderAction() } }
    }

    fun snapshotActionCallBack(image: Image?) {
        Platform.runLater {
            // Main.getStage().setIconified(false);
            mainStage.show()
        }
        codeImageView1.image = image
        val code = image?.let { QRCodeUtil.toDecode(it) }
        if (StringUtils.isNotEmpty(code)) {
            contentTextField.value=code
        }
        Platform.setImplicitExit(true)
    }

}